import { lazy } from 'react'
import { RouteObject } from 'react-router-dom'

import type { RouteConfig } from '#/router'

const enrtyPath = '/src/pages/'
const pages = import.meta.glob('/src/pages/**/*.tsx')
export const creatRoute = (permissions: RouteConfig[]) => {
  return permissions.map((item: RouteConfig) => {
    const Element = lazy(resolveComponent(item.key) as never)
    const route: RouteObject = {
      path: '/' + item.key,
      element: <Element />,
      children: []
    }
    if (!resolveComponent(item.key)) {
      delete route['element']
    }

    if (item.children && item.children.length) {
      route.children = creatRoute(item.children)
    }
    return route
  })
}

function resolveComponent(path: string) {
  return pages[`${enrtyPath}${path}/index.tsx`]
}
